#region using Statements

using System;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Windows.Live.SSO;

#endregion


public partial class _Default : System.Web.UI.Page
{
    private NameValueCollection _appSettings = ConfigurationManager.AppSettings;
    private bool _hasError = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        
        this.LabelDomainAppend.Text = HttpUtility.HtmlEncode(String.Format("[Append '{1}': {0}]", _appSettings["suffixAppend"], _appSettings["domain"]));
        this.LabelUserIdentification.Text = HttpUtility.HtmlEncode(String.Format("[IIS Authentication type: {0}]", Page.User.Identity.AuthenticationType));
        this.LabelScenarioName.Text = HttpUtility.HtmlEncode(String.Format("Scenario: {0}", GetScenarioName(_appSettings["scenario"])));

        if (ViewState["step"] == null)
        {
            ViewState["step"] = 0;
            this.LabelPortalUser.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelPortalUser.Text = HttpUtility.HtmlEncode("Press [Step 1] button to identify web-user");
            this.Button02.Enabled = false;
            this.Button04.Enabled = false;
            this.Button05.Enabled = false;
        }
    }

    protected void Button01_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(Page.User.Identity.Name))
        {
            _hasError = true;
            this.LabelPortalUser.Text = HttpUtility.HtmlEncode("Cannot identify the user.  Make sure anonymous access is not turned on in the IIS application.");
        }
        else
        {
            _hasError = false;

            //string currentUser = "hard-coded";
            string currentUser = Page.User.Identity.Name;

            ViewState["portalUser"] = currentUser;
            this.LabelPortalUser.Text = HttpUtility.HtmlEncode(currentUser);
            this.LabelPortalUser.ForeColor = System.Drawing.Color.Green;
            this.Button02.Enabled = true;
            this.Button04.Enabled = false;
            this.Button05.Enabled = false;
            this.LabelWindowsLiveUser.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelWindowsLiveUser.Text = HttpUtility.HtmlEncode("Press [Step 2] button to retrieve/concatenate user's LiveID");

            ViewState["step"] = 1;
        }
    }

    protected void Button02_Click(object sender, EventArgs e)
    {
        string wlUserID = WLID.GetWindowsLiveID(ViewState["portalUser"].ToString(), _appSettings["scenario"]);
        ViewState["windowsLiveUserID"] = wlUserID;

        if ((!wlUserID.Contains("@")) || (wlUserID.IndexOf("@") == 0))
        {
            _hasError = true;
            this.LabelWindowsLiveUser.ForeColor = System.Drawing.Color.Red;
            this.LabelWindowsLiveUser.Text = HttpUtility.HtmlEncode("The Windows Live ID for the user is invalid or the user cannot be found.");
        }
        else
        {
            _hasError = false;
            this.LabelWindowsLiveUser.Text = wlUserID;
            this.LabelWindowsLiveUser.ForeColor = System.Drawing.Color.Green;
            this.Button04.Enabled = true;
            this.Button05.Enabled = false;

            this.LabelSLT.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelSLT.Text = HttpUtility.HtmlEncode("Press [Step 4] button to retrieve Short Lived Ticket from LiveID SOAP Server");

            ViewState["step"] = 2;
        }
    }

    protected void Button04_Click(object sender, EventArgs e)
    {
        LiveSLT ticket = new LiveSLT(_appSettings["certThumb"],
                                     _appSettings["siteID"], this._appSettings["webProxy"],
                                     int.Parse(_appSettings["loginSeconds"]));

        string slt = ticket.GetSLT(ViewState["windowsLiveUserID"].ToString(), _appSettings["siteID"]);

        if ((String.IsNullOrEmpty(slt)) || (!ticket.Success))
        {
            _hasError = true;
            this.LabelSLT.Text = ticket.CustomExceptionMessage;
            this.LabelErrorCode.Text = HttpUtility.HtmlEncode(String.Format("Main Exception Code: {0}", ticket.ExceptionCode));
            this.LabelErrorText.Text = HttpUtility.HtmlEncode(ticket.ExceptionMessage);
            this.LabelInnerErrorCode.Text = HttpUtility.HtmlEncode(String.Format("Inner Exception Code: {0}", ticket.InnerExceptionCode));
            this.LabelInnerErrorText.Text = HttpUtility.HtmlEncode(ticket.InnerExceptionMessage);
        }
        else
        {
            _hasError = false;
            ViewState["slt"] = slt;

            this.LabelSLT.ForeColor = System.Drawing.Color.Green;
            this.LabelSLT.Text = HttpUtility.HtmlEncode(String.Format("Ticket received: {0}", slt));

            string redirectUrl = String.Empty;
            if (optSpaces.Checked)
            {
                redirectUrl = "http://spaces.live.com/?lc=1033";
            }
            else if (optSkyDrive.Checked)
            {
                redirectUrl = "http://skydrive.live.com/home.aspx?provision=1";
            }
            else
            {
                try
                {
                    redirectUrl = _appSettings["redirectURL"];
                }
                catch { }
            }
            if (String.IsNullOrEmpty(redirectUrl))
            {
                throw new ApplicationException("redirectURL is a required appSetting in the web.config");
            }

            string result = LiveRPS.CreateRedirectString(slt, redirectUrl, _appSettings["siteID"]);

            this.LabelRedirectionTarget.Text = HttpUtility.HtmlEncode(result);
            ViewState["URL"] = result;

            this.Button05.Enabled = true;
            this.LabeRedirect.ForeColor = System.Drawing.Color.DarkRed;
            this.LabeRedirect.Text = HttpUtility.HtmlEncode("Press [Step 5] button to be redirected to the selected Url above.");
        }
    }

    protected void Button05_Click(object sender, EventArgs e)
    {
        this.LabeRedirect.ForeColor = System.Drawing.Color.Green;
        this.LabeRedirect.Text = HttpUtility.HtmlEncode("Redirecting...");

        string sltUrl = ViewState["URL"].ToString();
        if (Request.Browser.EcmaScriptVersion.Major > 0)
        {
            string slt = ViewState["slt"].ToString();
            sltUrl = sltUrl.Substring(0, sltUrl.IndexOf("&slt"));
            string sltScript = String.Format("postSlt('{0}','{1}');", sltUrl, slt);
            ClientScript.RegisterStartupScript(typeof(Page), "SLT", sltScript, true);
        }
        else
        {
            Response.Redirect(sltUrl);
            Response.End();
        }
    }

    protected void OneClickButton_Click(object sender, EventArgs e)
    {
        Button01_Click(null, null);
        if (_hasError)
        {
            this.LabelDemoTwo.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelDemoTwo.Text = HttpUtility.HtmlEncode("Error occurred.  Check step 1 below.");
            return;
        }

        Button02_Click(null, null);
        if (_hasError)
        {
            this.LabelDemoTwo.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelDemoTwo.Text = HttpUtility.HtmlEncode("Error occurred.  Check step 2 below.");
            return;
        }

        Button04_Click(null, null);
        if (_hasError)
        {
            this.LabelDemoTwo.ForeColor = System.Drawing.Color.DarkRed;
            this.LabelDemoTwo.Text = HttpUtility.HtmlEncode("Error occurred.  Check step 4 below.");
            return;
        }

        Button05_Click(null, null);
    }

    private string GetScenarioName(string scenario)
    {
        switch (scenario.ToUpper())
        {
            case "A":
            case "1":
                return "Active Directory ID = Live ID (SAM w/ suffix or UPN)";
            case "B":
            case "2":
                return "XML Directory Lookup";
            case "C":
            case "3":
                return "Active Directory lookup of attribute with Live ID stored in it";
            default:
                return "Specified method is undefined";
        }
    }
}